package bro2Advanced.threads;

import java.util.concurrent.CyclicBarrier;

/**
 * 锁分类和JUC CyclicBarrier
 */
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        int numberOfThreads = 3;
        CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, () -> {
            // 当所有线程都到达障碍点时执行的操作
            System.out.println("所有线程都已到达屏障，进入下一阶段");
        });
    }

    static class Task implements Runnable {

        private final CyclicBarrier barrier;

        public Task(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "正在屏障处等待");
            try {
                barrier.await(); // 等待所有线程到达障碍点
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + " 已越过屏障.");
        }
    }
}
